import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import io.socket.client.IO;
import io.socket.client.Socket;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class t11 {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 64; i++) {

            Thread.sleep( 100);
            System.out.println("循环数"+i);
        //方式1：相当于继承了Thread类，作为子类重写run()实现
        new Thread() {
            public void run() {

                String url = "http://127.0.0.1:9090";
                try {
                    IO.Options options = new IO.Options();
                    options.transports           = new String[]{"websocket"};
                    options.reconnectionAttempts = 2;
                    // 失败重连的时间间隔
                    options.reconnectionDelay = 1000;
                    // 连接超时时间(ms)
                    options.timeout = 500;
                    // userId: 唯一标识 传给服务端存储
                    String randomUUID = IdUtil.randomUUID();
                    System.out.println("表示数"+randomUUID);

                    final Socket socket = IO.socket(url + "?userId="+ randomUUID, options);

                    socket.on(Socket.EVENT_CONNECT, args1 -> socket.send("hello..."));

                    // 自定义事件`connected` -> 接收服务端成功连接消息
                    socket.on("connected", objects -> log.debug("服务端1:" + objects[0].toString()));

                    // 自定义事件`push_data_event` -> 接收服务端消息
                    socket.on("push_data_event", objects -> log.debug("服务端2:" + JSONUtil.toJsonStr(objects)));

                    // 自定义事件`myBroadcast` -> 接收服务端广播消息
                    socket.on("myBroadcast", objects -> log.debug("服务端3：" + objects[0].toString()));

                    socket.connect();
                    while (true) {
                        Thread.sleep( RandomUtil.randomInt(3000, 100000));
                        // 自定义事件`push_data_event` -> 向服务端发送消息
                        socket.emit("push_data_event", "发送数据4 " + System.currentTimeMillis());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            };
        }.start();

        }

    }
}
